//
//  SearchUserController.m
//  collection
//
//  Created by 张靖 on 4/26/12.
//  Copyright (c) 2012 Tsinghua University. All rights reserved.
//

#import "SearchUserController.h"
#import "CollectionDataManager.h"
#import "UserProfileController.h"
#import "UserRelationCell.h"

@interface SearchUserController ()

@property (nonatomic, assign)   NSMutableArray* searchHistorySet;
@property (nonatomic, copy)   NSArray*    searchHints;
@property (nonatomic, retain)   NSMutableArray* searchResults;
@property (retain, nonatomic) IBOutlet UITableView *resultView;
@property (retain, nonatomic) IBOutlet UILabel *emptyHint;

- (IBAction)onClickBackBarButton:(id)sender;

- (void)filterContentForSearchText:(NSString*)searchText;
- (void)doSearch:(NSString*)searchText;

@end

@implementation SearchUserController

@synthesize searchHistorySet = _searchHistorySet;
@synthesize searchHints = _searchHints;
@synthesize searchResults   = _searchResults;
@synthesize resultView = _resultView;
@synthesize emptyHint = _emptyHint;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        CollectionDataManager* shardDataManager = [CollectionDataManager sharedInstance];
        self.searchHistorySet = shardDataManager.searchHistory;
        self.searchResults = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc {
    
    self.searchHints = nil;
    self.searchResults = nil;
    [_resultView release];
    [_emptyHint release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setResultView:nil];
    [self setEmptyHint:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Implementation of UISearchbarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    self.emptyHint.hidden = YES;
    self.resultView.hidden = YES;
    self.searchDisplayController.searchResultsTableView.hidden = NO;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self doSearch:searchBar.text];
}

#pragma mark - Implementation of UISearchDisplayDelegate
/*
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    
    [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    
    return YES;
}
*/
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    
    [self filterContentForSearchText:searchString];
    
    return YES;
}

#pragma mark - Implementation of UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [self.searchHints count];
    }
    else {
        return [self.searchResults count];
    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        static NSString* CellID1 = @"Cell";
        
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellID1];
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID1] autorelease];
        }
        
        cell.textLabel.text = [self.searchHints objectAtIndex:indexPath.row];
        
        return cell;
    }
    else {
        
        static NSString* CellID2 = @"UserRelationCellID";
        UserRelationCell* cell = (UserRelationCell*)[tableView dequeueReusableCellWithIdentifier:CellID2];
        if (cell == nil) {
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"UserRelationCell" owner:self options:nil];
            cell = [views objectAtIndex:0];
        }
        
        UserInfo* user = [self.searchResults objectAtIndex:indexPath.row];
        cell.avatarImageView.image = user.avatar;
        cell.nicknameLabel.text = user.nickname;
        cell.signatureLabel.text = user.signature;
        cell.actionButton.hidden = YES;
        
        return cell;
    }
}

#pragma mark - Implementation of UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString* searchText = cell.textLabel.text;
        [self doSearch:searchText];
    }
    else {
        // Go to User profile
        NSLog(@"haha");
        UserInfo* user = [self.searchResults objectAtIndex:indexPath.row];
        
        UserProfileController* userProfileController = [[UserProfileController alloc] initWithNibName:@"UserProfileController" bundle:nil];
        userProfileController.userID = user.userID;
        [self.navigationController pushViewController:userProfileController animated:YES];
        [userProfileController release];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Private methods

- (void)doSearch:(NSString *)searchText {
    
    [self.searchResults removeAllObjects];
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    
    NSSet* users = sharedDataManager.cachedUsers;
    for (UserInfo* user in users) {
        NSRange range = [user.nickname rangeOfString:searchText];
        if (range.location != NSNotFound) {
            [self.searchResults addObject:user];
            break;
        }
    }
    
    self.searchDisplayController.searchResultsTableView.hidden = YES;
    BOOL isNewWord = YES;
    for (NSString* str in self.searchHistorySet) {
        if ([str isEqualToString:searchText]) {
            isNewWord = NO;
            break;
        }
    }
    if (isNewWord) {
        [self.searchHistorySet addObject:searchText];
    }
    
    if ([self.searchResults count] > 0) {
        [self.resultView reloadData];
        self.resultView.hidden = NO;
    }
    else {
        self.resultView.hidden = YES;
    }
}

- (IBAction)onClickBackBarButton:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)filterContentForSearchText:(NSString *)searchText {
    
    NSPredicate* result = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    self.searchHints = [self.searchHistorySet filteredArrayUsingPredicate:result];
}

@end
